package com.act;

import java.util.ArrayList;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.adapter.AnswerAdapter;
import com.bean.Answer;
import com.bean.BaseBean;
import com.bean.UserInfo;
import com.common.Constant;
import com.common.LocalFileHelper;
import com.common.TextHttpResponseHandler;
import com.control.UserControl;
import com.xike.imageloader.core.ImageLoader;
import com.xike.kyt.R;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

public class Answer_DetailAct extends BaseAct implements View.OnClickListener {

	private static final int REQUEST_CODE_TO_COMMENT = 1;
	private static final int REQUEST_CODE_TO_LOGIN = 2;

	TextView tv_back, head_tv_comment, tv_answerNum;
	TextView tv_comment, tv_collect, tv_love;

	RelativeLayout layout_userInfo;
	TextView tv_userName, tv_info;
	TextView tv_questionTitle;
	TextView tv_content;
	ImageView img_userImage;

	ListView listView;
	AnswerAdapter adapter;
	ArrayList<Answer> comments = new ArrayList<Answer>();

	Answer answerDetail;

	long answerId;
	Bitmap defualtBitmap;

	Answer newComment;

	int loveNum = 0;

	boolean detailChanged = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_answer_detail);
		Bundle bundle = getIntent().getExtras();
		if (bundle != null && bundle.containsKey("answerId")) {
			answerId = bundle.getLong("answerId");
		}

		initViews();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_CODE_TO_LOGIN && resultCode > 0) {
			serviceGetDetail();
		} else if (requestCode == REQUEST_CODE_TO_COMMENT && resultCode > 0) {
			newComment = (Answer) data.getExtras().get("newComment");
			comments.clear();
			comments.add(newComment);
			ArrayList<Answer> resultAnswers = answerDetail.getComments();
			if (resultAnswers != null && resultAnswers.size() > 0) {
				comments.addAll(resultAnswers);
			}
			adapter.notifyDataSetChanged();
			MyUtil.setListViewHeightBasedOnChildren(listView);

			tv_answerNum.setText(comments.size() + " 条评论");
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void initViews() {
		BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.default_user_avator);
		defualtBitmap = bd.getBitmap();

		tv_back = (TextView) findViewById(R.id.headTitle_tv_back);
		head_tv_comment = (TextView) findViewById(R.id.answerDetail_headTitle_comment);

		tv_content = (TextView) findViewById(R.id.answerDetail_tv_content);
		tv_questionTitle = (TextView) findViewById(R.id.answerDetail_tv_quetionTitle);

		tv_answerNum = (TextView) findViewById(R.id.answerDetail_tv_answerNum);

		layout_userInfo = (RelativeLayout) findViewById(R.id.answerDetail_layout_user);
		layout_userInfo.setOnClickListener(this);

		tv_userName = (TextView) findViewById(R.id.user_tv_name);
		tv_info = (TextView) findViewById(R.id.user_tv_desc);
		img_userImage = (ImageView) findViewById(R.id.user_img_image);
		img_userImage.setImageBitmap(defualtBitmap);

		tv_comment = (TextView) findViewById(R.id.answerDetail_tv_comment);
		tv_collect = (TextView) findViewById(R.id.answerDetail_tv_collect);
		tv_love = (TextView) findViewById(R.id.answerDetail_tv_love);

		listView = (ListView) findViewById(R.id.answerDetail_listView);

		tv_back.setOnClickListener(this);
		tv_comment.setOnClickListener(this);
		head_tv_comment.setOnClickListener(this);
		tv_collect.setOnClickListener(this);

		adapter = new AnswerAdapter(this, comments, false);
		listView.setAdapter(adapter);

		serviceGetDetail();
	}

	@Override
	protected void updateViews() {
		UserInfo user = answerDetail.getUser();
		ArrayList<Answer> resultAnswers = answerDetail.getComments();

		MyUtil.setTextViewText(tv_userName, user.getShow_name(), 0, "未知用户");

		if (StringUtil.isNotNull(user.getInformation())) {
			tv_info.setText("认证:" + user.getInformation());
		} else {
			tv_info.setText("");
		}
		final String strTitle = answerDetail.getQuestion().getTitle();
		if (StringUtil.isNotNull(strTitle)) {
			tv_questionTitle.setVisibility(View.VISIBLE);
			tv_questionTitle.setText("问题：" + strTitle);
		} else {
			tv_questionTitle.setVisibility(View.GONE);
		}

		String strContent = answerDetail.getContent();

		final Html.ImageGetter imageGetter = new Html.ImageGetter() {

			public Drawable getDrawable(String source) {
				Drawable drawable = null;
				try {
					Bitmap bitmap = ImageLoader.getInstance().loadImageSync(source);
					drawable = new BitmapDrawable(bitmap);
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
				drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
				return drawable;
			};
		};
		tv_content.setText(Html.fromHtml(strContent, imageGetter, null));
		MyUtil.displayImageView(this, user.getAvator(), img_userImage, defualtBitmap, false);

		if (resultAnswers == null || resultAnswers.size() <= 0) {
			tv_answerNum.setText("暂无相关评论");
		} else {
			tv_answerNum.setText(resultAnswers.size() + " 条评论");
			comments.addAll(resultAnswers);
			adapter.notifyDataSetChanged();
			MyUtil.setListViewHeightBasedOnChildren(listView);
		}

		if (answerDetail.isIs_loved()) {
			tv_love.setText("已赞");
		} else {
			tv_love.setText("赞");
		}
		tv_love.setOnClickListener(this);
		loveNum = answerDetail.getLove_num();
		tv_love.append(loveNum > 0 ? "(" + loveNum + ")" : "");

		if (answerDetail.isIs_collected()) {
			tv_collect.setText("已收藏");
		} else {
			tv_collect.setText("收藏");
			tv_collect.setOnClickListener(this);
		}
		
		((ScrollView) findViewById(R.id.answerDetail_layout_content)).smoothScrollTo(0, 20);
		
	}

	private void serviceGetDetail() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("id", String.valueOf(answerId)));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_ANSWER_DETAIL, params);
		// 本地缓存
		if (LocalFileHelper.getInstance(this).fileIsExited(strUrl)) {
			Answer result = gson.fromJson(LocalFileHelper.getContentFromFile(strUrl), Answer.class);
			dealRequestResult(result);
			return;
		}

		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				super.onSuccess(statusCode, headers, responseString);
				Answer result = gson.fromJson(responseString, Answer.class);
				dealRequestResult(result);

			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(Answer_DetailAct.this, getResources().getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void dealRequestResult(Answer result) {
		if (result != null) {
			if (result.getError_code().equals(Constant.RESULT_CODE_SUCCESS)) {
				answerDetail = result;
				updateViews();
			} else {
				mToast.showToast(this, result.getError_description());
			}
		} else {
			mToast.showToast(this, getString(R.string.net_error));
		}
	}

	private void serviceAnswerLove() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("id", String.valueOf(answerId)));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_ANSWER_LOVE, params);
		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				super.onSuccess(statusCode, headers, responseString);
				BaseBean result = gson.fromJson(responseString, BaseBean.class);
				if (result != null && result.isReturnTrue()) {
					mToast.showToast(Answer_DetailAct.this, "赞成功");
					answerDetail.setIs_loved(true);
					detailChanged = true;
					tv_love.setText("已赞");
					loveNum++;
					tv_love.append(loveNum > 0 ? "(" + loveNum + ")" : "");
				} else {
					mToast.showToast(Answer_DetailAct.this, getResources().getString(R.string.net_error));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(Answer_DetailAct.this, getResources().getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void serviceAnswerCancelLove() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("id", String.valueOf(answerId)));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_ANSWER_CANCEL_LOVE, params);
		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				super.onSuccess(statusCode, headers, responseString);
				BaseBean result = gson.fromJson(responseString, BaseBean.class);
				if (result != null && result.isReturnTrue()) {
					mToast.showToast(Answer_DetailAct.this, "取消成功");
					answerDetail.setIs_loved(false);
					detailChanged = true;
					tv_love.setText("赞");
					loveNum--;
					tv_love.append(loveNum > 0 ? "(" + loveNum + ")" : "");
				} else {
					mToast.showToast(Answer_DetailAct.this, getResources().getString(R.string.net_error));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(Answer_DetailAct.this, getResources().getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void serviceAnswerCollect() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("id", String.valueOf(answerId)));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_ANSWER_COLLECT, params);
		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				super.onSuccess(statusCode, headers, responseString);
				BaseBean result = gson.fromJson(responseString, BaseBean.class);
				if (result != null && result.isReturnTrue()) {
					mToast.showToast(Answer_DetailAct.this, "收藏成功");
					tv_collect.setText("已收藏");
					// UserControl.setUserInfoChanged(true);
				} else {
					mToast.showToast(Answer_DetailAct.this, getResources().getString(R.string.net_error));
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(Answer_DetailAct.this, getResources().getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	@Override
	public void onClick(View v) {
		Intent it_anwer;
		switch (v.getId()) {
		case R.id.answerDetail_layout_user:
			intentToUserInfoAct();
			break;
		case R.id.headTitle_tv_back:
			if (detailChanged) {
				setResult(1);
			}
			finish();
			break;
		case R.id.answerDetail_headTitle_comment:
			if (UserControl.isLogined()) {
				it_anwer = new Intent(Answer_DetailAct.this, CommentAct.class);
				it_anwer.putExtra("answerId", answerDetail.getId());
				it_anwer.putExtra("answerContent", answerDetail.getContent());
				startActivityForResult(it_anwer, REQUEST_CODE_TO_COMMENT);
			} else {
				MyUtil.intentToLogin(this, REQUEST_CODE_TO_LOGIN);
			}

			break;
		case R.id.answerDetail_tv_comment:
			if (UserControl.isLogined()) {
				it_anwer = new Intent(Answer_DetailAct.this, CommentAct.class);
				it_anwer.putExtra("answerId", answerDetail.getId());
				it_anwer.putExtra("answerContent", answerDetail.getContent());
				startActivityForResult(it_anwer, REQUEST_CODE_TO_COMMENT);
			} else {
				MyUtil.intentToLogin(this, REQUEST_CODE_TO_LOGIN);
			}
			break;
		case R.id.answerDetail_tv_collect:
			if (UserControl.isLogined()) {
				serviceAnswerCollect();
			} else {
				MyUtil.intentToLogin(this, REQUEST_CODE_TO_LOGIN);
			}

			break;

		case R.id.answerDetail_tv_love:
			if (UserControl.isLogined()) {
				if (answerDetail.isIs_loved()) {
					serviceAnswerCancelLove();
				} else {
					serviceAnswerLove();
				}

			} else {
				MyUtil.intentToLogin(this, REQUEST_CODE_TO_LOGIN);
			}

			break;
		default:
			break;
		}
	}

	private void intentToUserInfoAct() {
		if (answerDetail == null) {
			return;
		}
		UserInfo user = answerDetail.getUser();
		if (user == null) {
			return;
		}
		Intent it_userInfo = new Intent(this, UserInfoAct.class);
		it_userInfo.putExtra("userId", user.getId());
		startActivity(it_userInfo);
	}
}
